/**
 * 面试题18-1：删除链表的节点
 */
public class Offer_18_I {
    public ListNode deleteNode(ListNode head, int val) {
        // 虚拟头节点
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode cur = dummyHead;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
                return dummyHead.next;
            }
            cur = cur.next;
        }
        return dummyHead.next;
    }

    public static void main(String[] args) {
        Offer_18_I solution = new Offer_18_I();
        ListNode head = new ListNode(4);
        head.next = new ListNode(5);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(9);
        solution.printListNode(head);

        ListNode ans = solution.deleteNode(head, 9);
        solution.printListNode(ans);
    }

    public void printListNode(ListNode node) {
        ListNode cur = node;
        System.out.print("[");
        while (cur != null) {
            System.out.print(cur.val + " -> ");
            cur = cur.next;
        }
        System.out.println("null]");
    }
}
